<template>
  <div class="content-editor">
    <!-- 模板选择阶段 -->
    <div v-if="!selectedTemplate && !isEditing" class="template-selector">
      <div class="selector-header">
        <h2>选择内容模板</h2>
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
      </div>
      
      <div class="templates-container">
        <div 
          v-for="template in templates" 
          :key="template.id" 
          class="template-card"
          @click="selectTemplate(template)"
        >
          <div class="template-thumbnail">
            <el-image 
              :src="template.thumbnail || defaultThumbnail" 
              fit="cover"
              :alt="template.name"
            />
          </div>
          <div class="template-info">
            <h3>{{ template.name }}</h3>
            <p>{{ template.description }}</p>
          </div>
          <div class="template-actions">
            <el-button type="primary">选择</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 内容编辑阶段 -->
    <div v-else class="editor-container">
      <div class="editor-header">
        <div class="header-left">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <h2 v-if="isEditing">编辑内容：{{ pageTitle }}</h2>
          <h2 v-else>创建新内容</h2>
        </div>
        
        <div class="header-right">
          <el-select v-model="pageStatus" placeholder="状态" style="width: 120px; margin-right: 15px;">
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="弃用" value="disabled" />
          </el-select>
          
          <el-button @click="previewContent">预览</el-button>
          <el-button v-if="!isEditing" @click="saveDraft">保存草稿</el-button>
          <el-button type="primary" @click="saveContent">{{ isEditing ? '保存' : '发布' }}</el-button>
        </div>
      </div>
      
      <div class="title-input">
        <el-input 
          v-model="pageTitle" 
          placeholder="输入页面标题" 
          size="large"
          maxlength="100"
          show-word-limit
        />
      </div>
      
      <!-- 动态表单区域 -->
      <div class="form-container">
        <!-- 使用对应的模板组件 -->
        <component 
          :is="getTemplateComponent()"
          v-model="contentData"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
// 导入模板组件
import NewsArticleTemplate from '@/components/admin/templates/NewsArticleTemplate.vue'
import ProductTemplate from '@/components/admin/templates/ProductTemplate.vue'
import ActivityTemplate from '@/components/admin/templates/ActivityTemplate.vue'

interface Template {
  id: number
  name: string
  description: string
  thumbnail?: string
}

interface ContentItem {
  id: number
  title: string
  template_id: number
  template_name: string
  status: 'published' | 'draft' | 'disabled'
  path: string
  created_at: string
  updated_at: string
  content: any
}

const router = useRouter()
const route = useRoute()
const isEditing = computed(() => !!route.params.id)

const templates = ref<Template[]>([])
const selectedTemplate = ref<Template | null>(null)
const pageTitle = ref('')
const pageStatus = ref<'published' | 'draft' | 'disabled'>('draft')
const contentData = reactive<any>({})
const defaultThumbnail = '/images/default-template.jpg'

// 获取模板列表
const fetchTemplates = async () => {
  try {
    // 从localStorage获取数据，如果没有则创建示例数据
    const storedTemplates = localStorage.getItem('contentTemplates')
    if (storedTemplates) {
      templates.value = JSON.parse(storedTemplates)
    } else {
      // 创建示例数据
      templates.value = [
        { 
          id: 1, 
          name: '新闻文章', 
          description: '适用于发布新闻、博客等文章类内容',
          thumbnail: 'https://via.placeholder.com/300x200?text=新闻文章'
        },
        { 
          id: 2, 
          name: '产品展示', 
          description: '适用于展示产品信息',
          thumbnail: 'https://via.placeholder.com/300x200?text=产品展示'
        },
        { 
          id: 3, 
          name: '活动页面', 
          description: '适用于展示活动、促销信息',
          thumbnail: 'https://via.placeholder.com/300x200?text=活动页面'
        }
      ]
      localStorage.setItem('contentTemplates', JSON.stringify(templates.value))
    }
  } catch (error) {
    console.error('获取模板列表失败', error)
  }
}

// 获取内容数据
const fetchContent = async (id: string | string[]) => {
  try {
    // 从localStorage获取数据
    const storedContents = localStorage.getItem('contentItems')
    if (storedContents) {
      const contents = JSON.parse(storedContents)
      const content = contents.find((item: ContentItem) => item.id === Number(id))
      
      if (content) {
        pageTitle.value = content.title
        pageStatus.value = content.status
        
        // 获取对应的模板
        const template = templates.value.find(t => t.id === content.template_id)
        if (template) {
          selectedTemplate.value = template
        }
        
        // 设置内容数据
        Object.assign(contentData, content.content)
      } else {
        ElMessage.error('内容不存在')
        router.push('/admin/content/list')
      }
    }
  } catch (error) {
    ElMessage.error('获取内容数据失败')
    console.error(error)
  }
}

// 选择模板
const selectTemplate = (template: Template) => {
  selectedTemplate.value = template
  
  // 根据模板类型初始化内容数据
  if (template.id === 1) { // 新闻文章
    Object.assign(contentData, {
      summary: '',
      content: '',
      cover_image: '',
      tags: [],
      meta_title: '',
      meta_description: '',
      meta_keywords: '',
      publish_date: new Date()
    })
  } else if (template.id === 2) { // 产品展示
    Object.assign(contentData, {
      product_name: '',
      price: 0,
      original_price: 0,
      brief: '',
      description: '',
      gallery: [],
      features: [''],
      specifications: [{ name: '', value: '' }],
      meta_title: '',
      meta_description: '',
      meta_keywords: ''
    })
  } else if (template.id === 3) { // 活动页面
    Object.assign(contentData, {
      banner: '',
      activity_time: [new Date(), new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)],
      location: '',
      description: '',
      meta_title: '',
      meta_description: '',
      meta_keywords: ''
    })
  }
}

// 获取对应的模板组件
const getTemplateComponent = () => {
  if (!selectedTemplate.value) return null
  
  const componentMap: Record<number, any> = {
    1: NewsArticleTemplate,
    2: ProductTemplate,
    3: ActivityTemplate
  }
  
  return componentMap[selectedTemplate.value.id] || null
}

// 保存草稿
const saveDraft = () => {
  pageStatus.value = 'draft'
  saveContent()
}

// 生成路径
const generatePath = () => {
  const slug = pageTitle.value
    .toLowerCase()
    .replace(/[^\w\s]/g, '')
    .replace(/\s+/g, '-')
  
  let path = ''
  if (selectedTemplate.value?.id === 1) {
    path = `/news/${slug}`
  } else if (selectedTemplate.value?.id === 2) {
    path = `/products/${slug}`
  } else if (selectedTemplate.value?.id === 3) {
    path = `/activities/${slug}`
  } else {
    path = `/content/${slug}`
  }
  
  return `${path}-${Date.now().toString(36)}`
}

// 保存内容
const saveContent = async () => {
  if (!pageTitle.value.trim()) {
    ElMessage.warning('请输入页面标题')
    return
  }
  
  if (!selectedTemplate.value) {
    ElMessage.warning('请选择内容模板')
    return
  }
  
  try {
    // 从localStorage获取数据
    let contents: ContentItem[] = []
    const storedContents = localStorage.getItem('contentItems')
    if (storedContents) {
      contents = JSON.parse(storedContents)
    }
    
    const now = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    if (isEditing.value) {
      // 更新现有内容
      const index = contents.findIndex(item => item.id === Number(route.params.id))
      if (index !== -1) {
        contents[index] = {
          ...contents[index],
          title: pageTitle.value,
          status: pageStatus.value,
          updated_at: now,
          content: { ...contentData }
        }
      }
    } else {
      // 创建新内容
      const newContent: ContentItem = {
        id: Date.now(),
        title: pageTitle.value,
        template_id: selectedTemplate.value.id,
        template_name: selectedTemplate.value.name,
        status: pageStatus.value,
        path: generatePath(),
        created_at: now,
        updated_at: now,
        content: { ...contentData }
      }
      contents.push(newContent)
    }
    
    // 保存到localStorage
    localStorage.setItem('contentItems', JSON.stringify(contents))
    
    ElMessage.success(isEditing.value ? '保存成功' : '创建成功')
    router.push('/admin/content/list')
  } catch (error) {
    ElMessage.error(isEditing.value ? '保存失败' : '创建失败')
    console.error(error)
  }
}

// 预览内容
const previewContent = () => {
  if (!pageTitle.value.trim()) {
    ElMessage.warning('请输入页面标题')
    return
  }
  
  if (!selectedTemplate.value) {
    ElMessage.warning('请选择内容模板')
    return
  }
  
  // 创建预览数据
  const previewData = {
    title: pageTitle.value,
    template_id: selectedTemplate.value.id,
    template_name: selectedTemplate.value.name,
    content: { ...contentData }
  }
  
  // 保存到localStorage
  localStorage.setItem('previewContent', JSON.stringify(previewData))
  
  // 打开预览页面
  window.open('/preview', '_blank')
}

// 返回
const goBack = () => {
  router.push('/admin/content/list')
}

onMounted(async () => {
  await fetchTemplates()
  
  if (isEditing.value) {
    fetchContent(route.params.id)
  }
})
</script>

<style scoped>
.content-editor {
  padding: 24px;
  background: #fff;
  min-height: 100%;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.templates-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.template-card {
  width: 280px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.template-thumbnail {
  height: 160px;
  overflow: hidden;
}

.template-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.template-info {
  padding: 15px;
}

.template-info h3 {
  margin: 0 0 10px;
  font-size: 18px;
}

.template-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
  height: 40px;
  overflow: hidden;
}

.template-actions {
  display: flex;
  justify-content: center;
  padding: 10px 15px 15px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.title-input {
  margin-bottom: 20px;
}

.form-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
}
</style>